/*
 moxl - Modular XML Library
 Copyright (c) 2007, Malcolm Sparks

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package moxl.dom;

/**
 * A default implementation of a XML QName.
 */
public class DefaultQualifiedName implements QualifiedName
{
	private final XmlNamespace namespace;
	private final String localName;

	public DefaultQualifiedName(XmlNamespace namespace, String localName)
	{
		if (namespace == null)
		{
			throw new IllegalArgumentException("ns cannot be null");
		}
		this.namespace = namespace;
		this.localName = localName;
	}

	public XmlNamespace getNamespace()
	{
		return namespace;
	}

	public String getLocalPart()
	{
		return localName;
	}

	@Override
	public int hashCode()
	{
		final int PRIME = 31;
		int result = 1;
		result = PRIME * result + ((localName == null) ? 0 : localName.hashCode());
		result = PRIME * result + ((namespace == null) ? 0 : namespace.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj)
	{
		if (this == obj)
		{
			return true;
		}
		if (obj == null)
		{
			return false;
		}
		if (!(obj instanceof QualifiedName))
		{
			return false;
		}
		final QualifiedName other = (QualifiedName) obj;
		if (localName == null)
		{
			if (other.getLocalPart() != null)
			{
				return false;
			}
		}
		else if (!localName.equals(other.getLocalPart()))
		{
			return false;
		}
		if (namespace == null)
		{
			if (other.getNamespace() != null)
			{
				return false;
			}
		}
		else if (!namespace.equals(other.getNamespace()))
		{
			return false;
		}
		return true;
	}

	@Override
	public String toString()
	{
		StringBuilder builder = new StringBuilder("[");
		if (!getNamespace().equals(DefaultXmlNamespace.getInstance()))
		{
			builder.append(getNamespace());
			builder.append(":");
		}
		builder.append(getLocalPart());
		builder.append("]");
		return builder.toString();
	}

}
